package cn.kgc.mcartoon.utils;

import io.jsonwebtoken.Claims;
import io.jsonwebtoken.JwtBuilder;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
import lombok.Data;
import org.springframework.stereotype.Component;

import java.util.Date;

@Data
@Component
public class JwtUtil {

    //设定一个密钥
    private static String secretKey = "m-cartoon";

    //设定一个过期时间 7天有效
    private static long exp = 60 * 60 * 24 * 7;

    /**
     *  生成Token
     * @param id
     * @param subject
     * @param isLogin
     * @return 生成的Token
     */
    public static String createJwt(String id,String subject,Boolean isLogin){
        //当前日期的时间戳
        long nowMillis = System.currentTimeMillis();

        //根据时间戳获取一个日期对象
        Date now = new Date(nowMillis);

        JwtBuilder jwtBuilder = Jwts.builder().setId(id)
                                              .setSubject(subject)
                                              .setIssuedAt(now)
                                              .signWith(SignatureAlgorithm.HS256,secretKey)
                                              .claim("isLogin",isLogin);

        if (exp > 0){
            jwtBuilder.setExpiration(new Date(nowMillis+exp *1000));
        }
        //返回token
        return jwtBuilder.compact();
    }

    /**
     * 解析token方法
     * @param token
     * @return 返回Claims对象
     */
    public static Claims parseJWT(String token){
        return Jwts.parser().setSigningKey(secretKey)
                            .parseClaimsJws(token)
                            .getBody();
    }
}
